# encoding: utf-8

import pymysql
from DataType.Sql.SqlDataType import SqlLoginDataType


class SqlOperator:
    def __init__(self):
        sql_login_datatype = SqlLoginDataType()
        if sql_login_datatype.name == "mysql":
            self.connection = pymysql.connect(
                host=sql_login_datatype.host,
                port=sql_login_datatype.port,
                user=sql_login_datatype.user,
                password=sql_login_datatype.password,
                db=sql_login_datatype.database)
            self.cursor = self.connection.cursor()
        else:
            raise Exception("未知的数据库类型")

    def sql_search(self, sql_cmd):
        self.cursor.execute(sql_cmd)
        result = self.cursor.fetchall()
        return result

    def sql_insert(self, sql_cmd):
        self.cursor.execute(sql_cmd)
        self.connection.commit()
        return self.cursor.rowcount

    def sql_update(self, sql_cmd):
        self.cursor.execute(sql_cmd)
        self.connection.commit()
        return self.cursor.rowcount

    def sql_delete(self, sql_cmd):
        self.cursor.execute(sql_cmd)
        self.connection.commit()
        return self.cursor.rowcount

    def __del__(self):
        self.cursor.close()
        self.connection.close()


if __name__ == '__main__':
    cmd_insert = "INSERT INTO `gamewebtools`.`test` (`test`) VALUES ('1');"
    cmd_search = "SELECT * FROM `gamewebtools`.`test`;"
    cmd_update = "UPDATE `gamewebtools`.`test` SET `test` = '2' WHERE (`test` = '1');"
    cmd_delete = "DELETE FROM `gamewebtools`.`test` WHERE (`test` = '2');"

    sql_operator = SqlOperator()
    sql_operator.sql_insert(cmd_insert)
    res = sql_operator.sql_search(cmd_search)
    print(res)
    sql_operator.sql_update(cmd_update)
    res = sql_operator.sql_search(cmd_search)
    print(res)
    sql_operator.sql_delete(cmd_delete)